#version 330 core

in vec3 colour;
in vec2 uv;
in vec3 surfaceNormal;

in vec3 toLight;
in vec3 toCam;

out vec4 out_Colour;

uniform sampler2D tex;
uniform float shininess;
uniform float reflectivity;
uniform float bumpiness;
uniform float alphafunc;

float intensity(vec3 color)
{
	return (color.r + color.g + color.b) / 3.0;
}

float get_rgb_height(vec2 uv)
{
	return intensity(texture2D(tex, uv).rgb);
}

void main(void)
{

	vec3 light_colour = vec3(1.0,1.0,0.95);

	vec3 normal = normalize(surfaceNormal);
	vec3 to_light = normalize(toLight);
	vec3 from_light = -to_light;
	vec3 to_cam = normalize(toCam);
	vec3 specular = pow(max(dot(reflect(from_light,normal),to_cam),0.0),shininess)*reflectivity*light_colour;
	vec3 diffuse = max(dot(normal,to_light),0.2)*light_colour;
	float bump_factor = 1.0;

	if (bumpiness > 0.05) {
		float tl = get_rgb_height(vec2(uv.x - 0.0078125, uv.y + 0.0078125));
		float t  = get_rgb_height(vec2(uv.x - 0.0078125, uv.y - 0.0078125));
		float tr = get_rgb_height(vec2(uv.x + 0.0078125, uv.y + 0.0078125));
		float r  = get_rgb_height(vec2(uv.x + 0.0078125, uv.y));
		float br = get_rgb_height(vec2(uv.x + 0.0078125, uv.y - 0.0078125));
		float b  = get_rgb_height(vec2(uv.x, uv.y - 0.0078125));
		float bl = get_rgb_height(vec2(uv.x -0.0078125, uv.y - 0.0078125));
		float l  = get_rgb_height(vec2(uv.x - 0.0078125, uv.y));
		float dX = (tr + 2.0 * r + br) - (tl + 2.0 * l + bl);
		float dY = (bl + 2.0 * b + br) - (tl + 2.0 * t + tr);
		vec3 bump = normalize(vec3(dX, dY, 1.0-bumpiness));
		vec3 E = normalize(-to_cam);
		float b_spec = pow(clamp(dot(reflect(to_light, bump), E), 0.0, 1.0), 1.0);
		float b_diff = dot(-E,bump);
		bump_factor = (b_diff + 0.1 * b_spec);
	}

	vec4 texdata = texture(tex,uv);

	out_Colour = (vec4(diffuse,1.0)*texdata+vec4(specular,texdata.a+intensity(specular)))*bump_factor;
	if (alphafunc > 1.5) {
		float a0 = out_Colour.a;
		float a1 = texture(tex,uv+vec2(-0.001,-0.001)).a;
		float a2 = texture(tex,uv+vec2(-0.001,0.0)).a;
		float a3 = texture(tex,uv+vec2(-0.001,0.001)).a;
		float a4 = texture(tex,uv+vec2(0.0,-0.001)).a;
		float a5 = texture(tex,uv+vec2(0.0,0.001)).a;
		float a6 = texture(tex,uv+vec2(0.001,-0.001)).a;
		float a7 = texture(tex,uv+vec2(0.001,0.0)).a;
		float a8 = texture(tex,uv+vec2(0.001,0.001)).a;
		out_Colour.a = smoothstep(0.45,0.55,(a0+a1+a2+a3+a4+a5+a6+a7+a8)/9.0);
	}else if (alphafunc > 0.5) {
		out_Colour.a = smoothstep(0.45,0.55,out_Colour.a);
	}

}
